package parser;

import renderernode.*;
import java.util.ArrayList;
public class Parser
{
	private int cursor;
	private int lineNumber;
	private char curChar;
	private String theHTML;
	private HTMLConstants theHTMLconstants;
	private Tree tree;
	private TreeNode currentNode;
	
	public Parser(String theHTML)
	{
		//may need to use FileReader class (GUI should be dumb)
		this.theHTML=theHTML;
		tree=new Tree();
		currentNode=tree.getRoot();
	}
	
	
	//i don't know why the parseNode has to return something but obviously the return down there are wrong since is going to stop the while loop
	//public TreeNode ParseNode()
	public void ParseNode()
	{
		loadChar();
		while(cursor < theHTML.length())
		{
			
			if(curChar == '<')
			{
				//return parseTag();
				parseTag();
			}
			else
			{
				//return parseText();
				parseText();
			}
		}
		
	}
	
	public void parseText()//it doesnt have to return anything,you just have to add the new TextNode to the currentNode
	{
		StringBuffer theText = new StringBuffer();
		do
		{
			theText.append(curChar);
			loadChar();
			
		}
		while(curChar != '<');
		TextNode parsedText=new TextNode(theText.toString());
		currentNode.addChild(parsedText);//this was added because before we didn't store the new textNode in the tree
		
		
	}
	
	//public TreeNode parseTag() we dont have to return anything here either just add to the tree and change the currentNode
	public void parseTag()
	{
		
		String tagName = parseTagName();
		
		if (theHTMLconstants.isOpeningTag(tagName))
		{
	
			try{
				TreeNode tagNode = theHTMLconstants.getInstance(tagName);
				//if this tag is a table - call parseTable
				currentNode.addChild(tagNode);
				if (!tagNode.isLeaf())
					currentNode = tagNode;
			}
			
			catch(Exception e){}
			
		}
		else
			currentNode = closeTag(currentNode,tagName,new ArrayList());
		
		
		
	
	}
	
	private String parseTagName()
	{
		StringBuffer theText = new StringBuffer();
		do
		{
			theText.append(curChar);
			loadChar();
			
		}
		while(curChar != '>');
		
		theText.append(curChar);//we repeat the while loop> we need a better algorithm on the while loops
		loadChar();
		
		return theText.toString();
	}

	private void loadChar()
	{
		curChar = theHTML.charAt(cursor);
		if(Character.getType(curChar) == Character.LINE_SEPARATOR)
		{
			lineNumber++;
		}
		cursor++;
	}

	
	public TreeNode closeTag(TreeNode currentNode,String tagName,ArrayList unclosedTags)
	{
		
		
		return; 
	}


}



